﻿jQuery(document).ready(function ($j) {    
    if (typeof (window.RadEditorCommandList) != "undefined") {
        //Referent Content
        window.Telerik.Web.UI.Editor.CommandList["RefContent"] = function (commandName, editor, args) {
            var elem = editor.getSelectedElement(); //returns the selected element.
            var argument;
            if (elem == null) {
                alert("Xin hãy chọn vùng nhập liệu!");
                return;
            }

            //if ((elem !== null) && elem.hasOwnProperty('tagName')) {
            //// handle property xxx of documentFragment as required
            //alert("Xin hãy chọn vùng nhập liệu!");
            //return;
            //}

            var that = jQuery(elem);
            var htmlListRef = that.closest('#list_order');
            //if (elem.tagName == "SPAN") {
            if (htmlListRef.html() != null) {
                editor.selectElement(elem);

                //var selElem = editor.getSelectedElement(); //get the selected element
                //var parentElem = selElem.parentNode;
                //alert(parentElem.innerHTML);

                argument = {
                    html: htmlListRef.html(),
                    width: htmlListRef.width(),
                    cols: htmlListRef.attr('cols'),
                    templ: htmlListRef.attr('templ'),
                    ipad: htmlListRef.attr('ipad'),
                    disImg: htmlListRef.attr('display_img'),
                    disTitle: htmlListRef.attr('display_title'),
                    disSapo: htmlListRef.attr('display_sapo')
                };
                //editor.selectElement(elem);
                ////argument = elem;
                //argument = elem.outerHTML;
            }
            else {
                //remove links if present from the current selection - because of JS error thrown in IE
                editor.fire("Unlink");

                //editor.fire("FontSize", { value: "4" }); //fire the FontSize command
                //editor.fire("ForeColor", { value: "red" });  //fire the ForeColor command

                //remove Unlink command from the undo/redo list
                var commandsManager = editor.get_commandsManager();
                var commandIndex = commandsManager.getCommandsToUndo().length - 1;
                commandsManager.removeCommandAt(commandIndex);

                var content = editor.getSelectionHtml();

                //var link = editor.get_document().createElement("A");
                //link.innerHTML = content;
                //argument = link;
                argument = "";
            }

            var myCallbackFunction = function (sender, args) {
                //http://demos.telerik.com/aspnet-ajax/editor/examples/clientsIdeapi/defaultcs.aspx
                editor.pasteHtml(args);
                //editor.set_html(args);
                //editor.pasteHtml(String.format("<a href={0} contentID={2}>{1}</a> ", genarateLink('', args.contentId), args.name, args.contentId));
            };
            var widthWindows = 810;
            var heightWindows = 670;

            //showExternalDialog(url (aspx/html file), argument, wIdth, height, callbackFunction, callbackArgs, title, modal, behaviors, showStatusbar, showTitlebar);
            editor.showExternalDialog('Ajax.aspx?typePage=RadEditor&p=DialogContentRef', argument, widthWindows, heightWindows, myCallbackFunction, null, 'Thêm link bài liên quan', true, window.Telerik.Web.UI.WindowBehaviors.Close + window.Telerik.Web.UI.WindowBehaviors.Move, true, true);
        };
        //Chen link

        window.Telerik.Web.UI.Editor.CommandList["Chenlink"] = function (commandName, editor, args) {
            var elem = editor.getSelectedElement(); //returns the selected element.            		
            var selText = editor.getSelection().getHtml();
            var argument;
            if (elem == null) {
                alert("Xin hãy chọn vùng nhập liệu!");
                return;
            }
            var that = jQuery(elem);
            //var selText = that.html();
            var htmlListRef = that.closest('#list_order');
            if (htmlListRef.html() != null) {
                editor.selectElement(elem);
                argument = {
                    html: htmlListRef.html(),
                    width: htmlListRef.width(),
                    cols: htmlListRef.attr('cols'),
                    templ: htmlListRef.attr('templ'),
                    ipad: htmlListRef.attr('ipad'),
                    disImg: htmlListRef.attr('display_img'),
                    disTitle: htmlListRef.attr('display_title'),
                    disSapo: htmlListRef.attr('display_sapo'),
                    dislink: htmlListRef.attr('titel_link')
                };
            }
            else {
                //remove links if present from the current selection - because of JS error thrown in IE
                editor.fire("Unlink");
                var commandsManager = editor.get_commandsManager();
                var commandIndex = commandsManager.getCommandsToUndo().length - 1;
                commandsManager.removeCommandAt(commandIndex);
                argument = "";
            }

            var myCallbackFunction = function (sender, args) {
                editor.pasteHtml(args);
            };
            var widthWindows = 750; //$j(window).wIdth();
            var heightWindows = 400; //$j(window).height();
            editor.showExternalDialog('Ajax.aspx?typePage=RadEditor&p=link&dislayText=' + selText, argument, widthWindows, heightWindows, myCallbackFunction, null, 'Thêm link bài liên quan', true, window.Telerik.Web.UI.WindowBehaviors.Close + window.Telerik.Web.UI.WindowBehaviors.Move, true, true);
        };


        //Embed vIdeo
        window.Telerik.Web.UI.Editor.CommandList["EmbedJwplayer"] = function (commandName, editor, args) {
            var elem = editor.getSelectedElement(); //returns the selected element.
            var argument;
            if (elem.tagName == "object") {
                editor.selectElement(elem);
                argument = elem;
                //argument = elem.outerHTML;
            }
            else {
                //remove Unlink command from the undo/redo list
                var commandsManager = editor.get_commandsManager();
                var commandIndex = commandsManager.getCommandsToUndo().length - 1;
                commandsManager.removeCommandAt(commandIndex);
                var content = editor.getSelectionHtml();

                var obj = editor.get_document().createElement("object");

                obj.innerHTML = obj.embed = content;
                obj.title = '';
                obj.plWidth = 450;
                obj.plHeight = 320;
                argument = obj;
            }

            var myCallbackFunction = function (sender, args) {
                editor.pasteHtml(args.embed);

                //var editorFiltersManager = editor.get_filtersManager();
                //editorFiltersManager.add(new Telerik.Web.UI.Editor.MozillaKeepFlash(editor.get_mozillaFlashOverlayImage()));

                editor.set_html(editor.get_html(true));
                //editor.set_mode(2); //http://www.telerik.com/help/aspnet-ajax/editor-set-mode.html, http://www.telerik.com/help/aspnet-ajax/editor-fullscreen-mode.html
            };
            editor.showExternalDialog('Ajax.aspx?typePage=RadEditor&p=DialogEmbedJwplayer', argument, 600, 500, myCallbackFunction, null, 'Thêm vIdeo', true, window.Telerik.Web.UI.WindowBehaviors.Close + window.Telerik.Web.UI.WindowBehaviors.Move, true, true);
        };
        
        //var imageManagerCommand = window.Telerik.Web.UI.Editor.CommandList["ImageManager"];
        //console.log(imageManagerCommand);

        //store the original command
        //var oldSetImagePropertiesCommand = window.Telerik.Web.UI.Editor.CommandList["SetImageProperties"];
        var oldSetImagePropertiesCommand = function (f, a, e) {
            var c = a.getSelectedElement();
            if (c && c.nodeName != "IMG") {
                c = null;
            }
            var d = new window.Telerik.Web.UI.EditorCommandEventArgs(f, null, c);
            window.Telerik.Web.UI.Editor.CommandList._getDialogArguments(d, "IMG", a, f);
            d.Element = c;
            var b = window.Telerik.Web.UI.Editor.CommandList.getCallbackFunction(e, function (j, i) {
                var h = i.get_value ? i.get_value() : i.Result;
                if (!h) {
                    return;
                }
                var $j = jQuery.noConflict();
                if (c && c.parentNode) {
                    var g = new window.Telerik.Web.UI.Editor.GenericCommand(a.getLocalizedString(f), a.get_contentWindow(), a);
                    c.parentNode.replaceChild(h, c);
                    $j(h).after('<p>' + $j(h).attr('alt') + '</p>');
                    a.executeCommand(g);
                } else {
                    a.pasteHtml(window.Telerik.Web.UI.Editor.Utils.getOuterHtml(h), f);
                }
            });
            if (f == "SetImageProperties") {
                a.showDialog("ImageProperties", d, b);
            } else {
                a.showDialog("InsertImage", d, b);
            }
            return false;
        };

        //var abc = window.Telerik.Web.UI.Editor.CommandList["ImageManager"];
        //alert(abc);

        window.Telerik.Web.UI.Editor.CommandList["SetImageProperties"] = function (commandName, editor, args) {
            var elem = editor.getSelectedElement();
            var typeId;
            var inmemoryId;
            var savedId;
            var pageControlName;

            //get the selected tag
            editor.selectElement(elem);
            var selection = editor.getSelection();
            var selectionHTML = selection.getHtml();
            //attempt to retrieve the parameters we need from the tags
            //attributes
            typeId = window.$telerik.$(selectionHTML).attr("typeId");
            savedId = window.$telerik.$(selectionHTML).attr("savedId");
            inmemoryId = window.$telerik.$(selectionHTML).attr("inMemoryId");
            pageControlName = window.$telerik.$(selectionHTML).attr("pageControlName");

            //check if this is a dynamic page control place holder
            if (typeId != null && savedId != null && inmemoryId != null && pageControlName != null) {
                //user has selected an dynamic page control and is trying to edit it using the image manager - must prevent this!
                alert('This is a dynamic page control, please click Edit Page Control to edit it');
                return; //disable the browsers context menu
            }
            else {
                oldSetImagePropertiesCommand(commandName, editor, args);
            }
        };

        //Empty
        window.Telerik.Web.UI.Editor.CommandList["RefContent1"] = function (commandName, editor, args) {
            if (editor.getSelectionHtml() != "") {
                editor.fire("FontSize", { value: "4" }); //fire the FontSize command
                editor.fire("ForeColor", { value: "red" }); //fire the ForeColor command
            }
            else {
                alert("Please, select some text!");
                args.set_cancel(true);
            }

            //editor.pasteHtml('<span style="wIdth:200px;border: 1px dashed #bb0000;background-color: #fafafa;color: blue;"> ' + new Date() + ' </span>');
            //editor.set_html(""); //set empty content
        };

        //MultiImageUpload
        window.Telerik.Web.UI.Editor.CommandList["MultiImageUpload"] = function (commandName, editor, args) {
            var elem = editor.getSelectedElement(); //returns the selected element.
            if (elem == null) {
                alert("Hãy chọn vị trí chèn dữ liệu!");
                return;
            }
            var myCallbackFunction = function (sender, args) {
                editor.pasteHtml(args);
            };

            editor.showExternalDialog('SP/MultiUpload.aspx', null, 800, 600, myCallbackFunction, null, 'Upload nhiều ảnh', true, window.Telerik.Web.UI.WindowBehaviors.Close + window.Telerik.Web.UI.WindowBehaviors.Move, true, true);
        };
        
        //EmbedTopic
        window.Telerik.Web.UI.Editor.CommandList["EmbedTopic"] = function (commandName, editor, args) {
            var myCallbackFunction = function (sender, args) {
                editor.pasteHtml(args);
            };
            var id = getURLParameter(location.href, 'id');
            editor.showExternalDialog('Ajax.aspx?typePage=RadEditor&p=EmbedTopic&id='+id, null, 600, screen.height-220, myCallbackFunction, null, 'Nhúng dòng sự kiện', true, window.Telerik.Web.UI.WindowBehaviors.Close + window.Telerik.Web.UI.WindowBehaviors.Move, true, true);
        };
        
        //InsertBoxImage
        window.Telerik.Web.UI.Editor.CommandList["InsertBoxImage"] = function (commandName, editor, args) {
            var elem = editor.getSelectedElement(); //returns the selected element.
            if (elem == null) {
                alert("Hãy chọn vị trí chèn dữ liệu!");
                return;
            }
            editor.pasteHtml("<table class='contentimg'><tr><td class='img'></td></tr><tr><td class='note'></td></tr></table>");
        };
        
        //InsertBoxContent
        window.Telerik.Web.UI.Editor.CommandList["InsertBoxContent"] = function (commandName, editor, args) {
            var elem = editor.getSelectedElement(); //returns the selected element.
            if (elem == null) {
                alert("Hãy chọn vị trí chèn dữ liệu!");
                return;
            }
            editor.pasteHtml("<table class='contentbox'><tr><td></td></tr></table>");
        };
        
        //Webpreview
        window.Telerik.Web.UI.Editor.CommandList["WebPreview"] = function (commandName, editor, args) {
            var title = getTitlePost();
            var sapo = getSapoPost();
            var time = getTimePost();
            var alias = getAliasPost();
            var argument = {html:editor.get_html(), title:title,sapo:sapo,time:time,alias:alias};
            editor.showExternalDialog('/SP/Preview.aspx', argument, 800, 600, null, null, 'Xem trước chi tiết', true, window.Telerik.Web.UI.WindowBehaviors.Close + window.Telerik.Web.UI.WindowBehaviors.Move, true, true);
        };
        
        //Webpreview
        window.Telerik.Web.UI.Editor.CommandList["HomePreview"] = function (commandName, editor, args) {
            var title = getTitlePost();
            var titleOther = getTitleOtherPost();
            var sapo = getSapoPost();
            var sapoOther = getSapoOtherPost();
            var img = getImagePost();
            var argument = { html: editor.get_html(), title: title, titleOther: titleOther, sapo: sapo, sapoOther: sapoOther, img: img };
            editor.showExternalDialog('/SP/PreviewHomeWidget.aspx', argument, 750, 600, null, null, 'Xem trước nổi bật chuyên mục', true, window.Telerik.Web.UI.WindowBehaviors.Close + window.Telerik.Web.UI.WindowBehaviors.Move, true, true);
        };
    }
});

